import dynamic from 'next/dynamic'
import Footer from '@c/footer'
import Responsive from '@c/responsive'
import HFilmList from '@c/h-film-list'
import { getPageData } from '@/api/home'
import { PAGE_INFO } from '@/constant'
import { useScrollSessionStore } from '@/utils/hooks'
import { useEffect, useMemo } from 'react'
import EventBus from '@/utils/emitter'

const GuideDownload = dynamic(() => import('@c/guide-download'))
const Banner = dynamic(() => import('@c/banner'))

const Index = props => {
  const pageScroll = 'dramaScroll'
  useScrollSessionStore(pageScroll)
  useEffect(() => {
    const top = sessionStorage.getItem(pageScroll) || 0
    window.scroll(0, top)
  }, [])

  const { headers, cardsGroup, url } = props
  const banners = useMemo(() => (headers ? headers : []).filter(item => item.name), [headers])

  useEffect(() => {
    getPageData('电视剧', {
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(res => {
      EventBus.emit('firstLevelPage', false, res?.data?.cardsGroup || [])
      EventBus.emit('updateBanner', false, res?.data?.headers || [])
    })

    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [])
  return (
    <>
      {banners.length && <Banner data={banners} url="drama" />}
      <Responsive>
        {cardsGroup.map((item, index) => {
          const GuideNode = ({ item, url }) => {
            return (
              <>
                <HFilmList lessItems data={item} source={url} top={50} />
                <GuideDownload top={10} bottom={56} />
              </>
            )
          }
          if (!index) {
            return <GuideNode item={item} url={url} key={index} />
          }
          return <HFilmList lessItems data={item} key={index} source={url} top={24} />
        })}
        <Footer />
      </Responsive>
    </>
  )
}
export default Index

export async function getServerSideProps() {
  const pageType = {
    url: '/drama',
    title: '电视剧',
    type: 'drama',
    filter: '电视剧片库'
  }

  const res = await getPageData(pageType.title, {})
  let layoutProps = {}
  try {
    layoutProps = {
      noSomeMetaInfo: false,
      url: pageType.url,
      ...PAGE_INFO[pageType.type]
    }
  } catch (error) {}

  return {
    props: {
      headers: [...(res?.data?.headers ? res?.data?.headers : [])],
      cardsGroup: [...(res?.data?.cardsGroup ? res?.data?.cardsGroup : [])],
      pageType,
      url: pageType.url,
      layoutProps
    }
  }
}
